package movie.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import movie.entity.Film;
import movie.service.FilmFindAllService;
import movie.service.FilmInsertService;


@Controller
public class FilmInsertController {

	@Autowired
	private FilmInsertService filmInsertService;
	@Autowired
	private FilmFindAllService filmFindAllService;
	
	@RequestMapping(value = "/filmInsert", method = RequestMethod.GET)
	public String get(Model model) {
		List<Film> films = filmFindAllService.findAll();
		for(Film film:films)
		{
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");		
			film.setReleaseDateString(format1.format(film.getReleaseDate()));				
		}
		model.addAttribute("films", films);
		return "Film/FilmInsert";
	}
	

	@RequestMapping(value = "/filmInsert", method = RequestMethod.POST)
	public String post(Film film,Model model) {
	
//		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		
//		try {
//			film.setReleaseDate(new java.sql.Timestamp(format1.parse(film.getReleaseDateString()).getTime()));
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		if(film.getFilmName().equals("") || film.getDirector().equals("") || film.getCover().equals("") || film.getType().equals("") 
				|| film.getLeads().equals("") || film.getCountry().equals("") || film.getFilmLength()==null || 
				film.getReleaseDate()==null || film.getScore()==0 || film.getIntroduction().equals("") ||
				film.getReying()==null || check(film.getFilmName())==1)
		{
			List<Film> films = filmFindAllService.findAll();
			for(Film film11:films)
			{
				SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");		
				film11.setReleaseDateString(format1.format(film11.getReleaseDate()));				
			}
			model.addAttribute("films", films);
			model.addAttribute("cuowu", 1);
			return "Film/FilmInsert";
		}
		
		int rows = filmInsertService.insertFilm(film);
		List<Film> films = filmFindAllService.findAll();
		model.addAttribute("films", films);
		
		
		//forward
		return "redirect:/filmFindAll";
	}
	
	@GetMapping("/checkByFilmName")
	public @ResponseBody int check(String filmName) {
		int result = filmInsertService.checkByFilmName(filmName);
		return result;
	}
}
